package com.sdkx.wear_os.app

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.sdkx.wear_os.ui.activity.ErrorActivity
import com.sdkx.wear_os.utils.*
import com.sdkx.wear_os.utils.ExceptionHandle.getExceptionInfo
import com.sdkx.wear_os.utils.ToastLogUtils.logUtil
import io.fastkv.FastKV
import io.fastkv.FastKVConfig


/**
 * @author ddy
 *application基类
 */
class MyApplication : Application(), ViewModelStoreOwner {
    private lateinit var mAppViewModelStore: ViewModelStore

    private var mFactory: ViewModelProvider.Factory? = null

    //伴生属性
    companion object {
        //屏幕宽px
        private var width = 0

        //屏幕高px
        private var height = 0

        //屏幕密度dpi
        private var density = 0f

        //屏幕宽dp
        private var walgreenWidth = 0

        //屏幕高dp
        private var screenHeight = 0

        lateinit var application: Application

        //持久化保存
        lateinit var fastKV: FastKV

        //用于添加activity的集合
        private val mList: MutableList<Activity> = mutableListOf()
        fun getWidth(): Int {
            return width
        }

        fun getHeight(): Int {
            return height
        }

        fun getWalgreenWidth(): Int {
            return walgreenWidth
        }

        fun getScreenHeight(): Int {
            return screenHeight
        }

        fun getDensity(): Float {
            return density
        }

        //将启动的进程添加进入list中
        fun addActivity(activity: Activity) {
            mList.add(activity)
        }


        //将list中的activity全部销毁
        fun exit() {
            for (activity in mList) {
                activity.finish()
            }
        }
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        //判断是否是debug
        if (!isApkInDebug(this)) {
//            处理异常信息防止崩溃
            catchException()
        }
    }

    override fun onCreate() {
        super.onCreate()
        //实例化上下文
        application = this
        mAppViewModelStore = ViewModelStore()
        FastKVConfig.setLogger(FastKVLogger)
        FastKVConfig.setExecutor(ChannelExecutor(4))
        fastKV = FastKV.Builder(
            savePath().absolutePath,
            "wear_os"
        ).build()
        //获取屏幕属性
        screen()
    }

    override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore
    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, this.getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }


    private fun screen() {
        val dm = Resources.getSystem().displayMetrics
        // 屏幕宽度(像素)
        width = dm.widthPixels
        // 屏幕高度(像素)
        height = dm.heightPixels
        // 屏幕密度(0.75 / 1.0 / 1.5)
        density = dm.density
        // 屏幕密度dpi(120 / 160 / 240)
        val densityDpi = dm.densityDpi
        // 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
        // 屏幕宽度(dp)
        walgreenWidth = ((width / density).toInt())
        // 屏幕高度(dp)
        screenHeight = ((height / density).toInt())
    }

    /**
     * 崩溃详细信息
     */
    private fun catchException() {
        Handler(Looper.getMainLooper()).post {
            while (true) {
                try {
                    Looper.loop()
                } catch (e: Exception) {
                    val error = getExceptionInfo(e)
                    logUtil("全局错误", error)
                    val intent = Intent(this, ErrorActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    intent.putExtra("error", "$e\n---------------\n$error")
                    startActivity(intent)
                }
            }
        }
        Thread.setDefaultUncaughtExceptionHandler { t, e -> //try-catch子线程的所有异常。
            val error = getExceptionInfo(e)
            val intent = Intent(this, ErrorActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.putExtra("error", "$e\n---------------\n$error")
            startActivity(intent)
        }
    }
}